package org.example.controller;

import lombok.extern.slf4j.Slf4j;
import org.example.anno.Log;
import org.example.pojo.Result;
import org.example.utils.AliyunOSSOperator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
public class UpLoadController {

    private final AliyunOSSOperator aliyunOSSOperator;

    public UpLoadController(AliyunOSSOperator aliyunOSSOperator) {
        this.aliyunOSSOperator = aliyunOSSOperator;
    }

    /**
     * 文件上传本地磁盘
     *
     * @param file
     * @return
     * @throws IOException
     */
//    @PostMapping("/upload")
//    public Result upload(String name, Integer age, MultipartFile file) throws IOException {
//        log.info("接受参数:{},{},{}", name, age, file.getOriginalFilename());
//        //原文件名字
//        String originalFil = file.getOriginalFilename();
//        //新文件名字 保证文件名不重复
//        assert originalFil != null;
//        String extension = originalFil.substring(originalFil.lastIndexOf("."));
//        String newFileName = UUID.randomUUID().toString() + extension;
//        //保存文件
//        file.transferTo(new File("/Users/zake/Documents/java_learing/web-AI/web-management" +
//                "/src/main/java/" + newFileName));
//        return Result.success();
//
//    }
    @Log
    @PostMapping("/upload")
    public Result upLoad(MultipartFile file) throws Exception {
        log.info("接受参数:{}", file.getOriginalFilename());
        String originalFilename = file.getOriginalFilename();
        //将文件交给阿里云oss
        assert originalFilename != null;
        String url = aliyunOSSOperator.upload(file.getBytes(), originalFilename);
        log.info("文件上传成功，url:{}", url);
        return Result.success(url);//返回文件路径
    }
}
